package com.bocai.kelala.ui.travel.main.act;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.CarInfoBean;
import com.bocai.kelala.bean.MessageEvent;
import com.bocai.kelala.pay.alipay.AlipayApi;
import com.bocai.kelala.pay.simcpux.WxPayApi;
import com.bocai.kelala.ui.travel.main.contract.VehicleDetailContract;
import com.bocai.kelala.ui.travel.main.module.VehicleDetailModule;
import com.bocai.kelala.ui.travel.main.presenter.VehicleDetailPresenter;
import com.bocai.kelala.util.SP;
import com.bocai.kelala.util.ToastUitl;
import com.bocai.kelala.widget.AlertDialog;
import com.bocai.kelala.widget.LocalImageHolderView;
import com.bocai.kelala.widget.PayPopupWindow;
import com.bocai.kelala.widget.SelectDatePopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuanfei on 2017/6/12.
 * 车辆详情
 */

public class VehicleDetailActivity extends BaseActivity implements View.OnClickListener, VehicleDetailContract.view {


    TimePickerView pickerView;
    SelectDatePopupWindow popupWindow;
    PayPopupWindow payPopupWindow;
    String orderId;
    @Inject
    VehicleDetailPresenter presenter;
    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.tv_vehicle_num)
    TextView tvVehicleNum;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_start_address)
    TextView tvStartAddress;
    @BindView(R.id.tv_end_address)
    TextView tvEndAddress;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_car_age)
    TextView tvCarAge;
    @BindView(R.id.tv_car_name)
    TextView tvCarName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.main)
    LinearLayout main;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.btn_select_data)
    Button btnSelectData;
    List<CarInfoBean.CarImagesBean> list = new ArrayList<>();
    CarInfoBean bean = new CarInfoBean();
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.ll_modify)
    LinearLayout llModify;

    @Override
    public int getLayoutId() {
        return R.layout.act_vehicle_detail;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new VehicleDetailModule(this)).inject(this);
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        initToolbar("车辆详情");
        initBack(imgBack,llBack);
        popupWindow = new SelectDatePopupWindow(this, this);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha((float) 1);
            }
        });
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/value_bold.otf");
        tvMoney.setTypeface(typeFace);

        orderId = getIntent().getStringExtra("orderId");
        presenter.getCarInfo(orderId);

    }

    public void setPage() {
        convenientBanner.startTurning(3000);
        if (list.size() <= 1) {
            convenientBanner.setCanLoop(false);
        } else {
            convenientBanner.setCanLoop(true);
        }
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView(VehicleDetailActivity.this);
                    }
                }, list);
    }

    @OnClick({R.id.btn_select_data,R.id.ll_modify})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_select_data:
//                pickerView.show();
                popupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.ll_modify:
                setDialog();
                break;

        }
    }

    public void setDataView() throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        // 指定一个日期
        final Date date1 = dateFormat.parse(bean.getBeginTime());

        final Date date2 = dateFormat.parse(bean.getEndTime());
        // 对 calendar 设置为 date 所定的日期

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (date.before(date1)){
                    showErrorTip("选择时间早于开始时间");
                }else if (date.after(date2)){
                    showErrorTip("选择时间晚于结束时间");
                }else {
                    popupWindow.setDate(date);
                    backgroundAlpha(0.5f);
                    popupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM, 0, 0);
                }

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                .setRangDate(calendar1, calendar2)
                .build();
        pickerView.setDate(calendar1);//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
//        pickerView.show();

        pickerView.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (!TextUtils.isEmpty(popupWindow.getData())) {
                    backgroundAlpha(0.5f);
                    popupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM, 0, 0);
                }
            }
        });
        payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                showErrorTip("抢单成功");
                setResult(27);
                finish();
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if ("11".equals(event.msg)){
            payPopupWindow.dismiss();
            showErrorTip("抢单成功");
            setResult(27);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_select_date:
                popupWindow.dismiss();
                pickerView.show();
                break;
            case R.id.btn_immediately_car:
                presenter.grabOrder(orderId,popupWindow.getData());
                break;
            case R.id.btn_confirm_pay:
                if (payPopupWindow.getPayType() == 0){
                    presenter.orderPay("alipayagency",orderId);
                }else {
                    presenter.orderPay("weixinagency",orderId);
                }

                break;
        }
    }

    @Override
    public void grabOrderSuccess() {
        popupWindow.dismiss();
        backgroundAlpha(0.5f);
        payPopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void getCarInfoSuccess(CarInfoBean bean) {
        this.bean = bean;
        tvVehicleNum.setText(bean.getApplySeats()+"座大客车");
        tvMoney.setText(bean.getPrice()+"");
        payPopupWindow = new PayPopupWindow(this,bean.getPrice()+"",this);
        payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        tvStartAddress.setText(bean.getOriginCity());
        tvEndAddress.setText(bean.getArriveCity());
        tvStartTime.setText(bean.getBeginTime());
        tvEndTime.setText(bean.getEndTime());
        tvCarAge.setText(bean.getCarAge()+"年");
        if (!TextUtils.isEmpty(bean.getContactPhone())) {
            String bb = bean.getContactPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
            tvPhone.setText(bb);
        }
        if (!TextUtils.isEmpty(bean.getContactName())) {
            String aa = bean.getContactName().substring(0, 1);
            tvCarName.setText(aa + "**");
        }
        list = bean.getCarImages();
        setPage();
        try {
            setDataView();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void orderPaySuccess(String result) {
//        showErrorTip("支付成功");
        if (payPopupWindow.getPayType() == 0) {
            AlipayApi alipayApi = new AlipayApi(this);
            alipayApi.payV2(result);
        }else {
            WxPayApi wxPayApi = new WxPayApi(this);
            wxPayApi.pay(result);

        }
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {

        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            showShortToast(msg);
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }else if (msg.equals("0004")){
            setResult(27);
            finish();
        }else if (msg.equals("还未通过认证")){
            if ((int) SP.get(this,"ApprovalStatus",0) == 0){
                ToastUitl.showShort("认证未申请");
            } else if ((int)SP.get(this,"ApprovalStatus",0) == -1){
                ToastUitl.showShort("审核未通过");
            }else if ((int)SP.get(this,"ApprovalStatus",0) == 1){
                ToastUitl.showShort("审核中");
            }
            finish();
        }else {
            showShortToast(msg);
        }
    }
    public void setDialog(){
        new AlertDialog(mContext).builder().setTitle("线路是否要修改?").setMsg("线路的修改后，价格会变化")
                .setPositiveButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VehicleDetailActivity.this,ModifyAddressActivity.class);
                intent.putExtra("orderId",orderId);
                intent.putExtra("startName",bean.getOriginCity());
                intent.putExtra("endName",bean.getArriveCity());
                startActivityForResult(intent,234);
            }
        }).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 234&&resultCode == 234){
            finish();
        }
    }
}
